import {ModalForm, ProFormSelect, ProFormText, ProFormTreeSelect, DrawerForm} from "@ant-design/pro-components";
import IHttp, {IAxiosResponse} from "@/services/http.service";
import React, {useEffect, useState} from "react";
import {Form, message} from "antd";
import { firstValueFrom } from "rxjs"
import environment from "@/environment";
import IHelper from "@/services/helper.service";

type CreateFormProps = {
  title?: string
  desc?: string
  bili_type?: string
  common_tag?: string[]
  dy_tag?: string[]
  ks_type?: string
}

type IProps = {
  item: API.PubTemplateItem | undefined
  onCancel: () => void
  onRefreshTable: () => void
}

export default function PubTemplateCreateForm({item, onCancel, onRefreshTable}: IProps) {
  const [form] = Form.useForm<CreateFormProps>();
  const open = Boolean(item)
  useEffect(() => {
    if (open) {
      const initialData: CreateFormProps = {
        title: item?.title || "", 
        desc: item?.desc || "", 
        common_tag: (item?.common_tag || "").split(",").filter(e => e),
        bili_type: item?.bili_type || "",
        dy_tag: (item?.dy_tag || "").split(",").filter(e => e),
        ks_type: item?.ks_type || "",
      }
      form.setFieldsValue(initialData)
    }
  }, [open])
  return (
    <DrawerForm<CreateFormProps>
      width={360}
      open={open}
      form={form}
      title={item?.id ? "编辑模板" : "新建模板"}
      onFinish={async (values) => {
        const postData = {
          title: values.title || "", 
          desc: values.desc || "",
          bili_type: values.bili_type,
          common_tag: (values.common_tag || []).join(","),
          dy_tag: (values.dy_tag || []).join(","),
          ks_type: values.ks_type || "",
        }
        if (Object.values(postData).some(e => !e)) {
          message.error("信息不完整！")
          return
        }
        let res: IAxiosResponse | undefined = undefined
        if (item?.id) {
          res = await firstValueFrom(IHttp.updatePubTemplate(item.id, postData))
        } else {
          res = await firstValueFrom(IHttp.createPubTemplate(postData))
        }
        if (res?.status) {
          message.success(item?.id ?  "更新成功" : "创建成功")
          onRefreshTable()
        }
        return true
      }}
      drawerProps={{
        destroyOnClose: true,
        onClose: onCancel,
        maskClosable: false,
      }}
    >
      <ProFormText
        name="title"
        label="标题"
        tooltip="最长为 24 位"
        placeholder="请输入名称"
      />
      <ProFormText
        name="desc"
        label="介绍"
        tooltip="最长为 24 位"
        placeholder="请输入介绍"
      />
      <ProFormSelect
        name="common_tag"
        label="通用Tag"
        mode="multiple"
        showSearch
        request={async ({keyWords}) => {
          if (!keyWords) return []
          return [{label: keyWords, value: keyWords}]
        }}
      />
      
      <ProFormTreeSelect
        name="bili_type"
        label="Bili 分类"
        request={async () => {
          let res = await firstValueFrom(IHttp.getBiliTypeList())
          if (!res.status) {
            return []
          }
          const treeData = res.data.map((item: any) => {
            return {
              ...item, title: item.name, value: item.id,
              disabled: true,
              children: (item.children || []).map((child: any) => {
                return {...child, title: `${child.name} - [${child.desc.substring(0, 10)}...]`, value: `${child.name}_${child.id}`}
              })
            }
          })
          return treeData
        }}
      />
      <ProFormTreeSelect
        name="ks_type"
        label="快手 分类"
        request={async () => {
          let res = await firstValueFrom(IHttp.getKsTypeList())
          if (!res.status) {
            return []
          }
          const treeData = res.data.map((item: any) => {
            return {
              ...item, title: item.firstDomain, value: item.firstDomain,
              disabled: true,
              children: (item.secondDomain || []).map((child: any) => {
                return {title: child, value: `${item.firstDomain}_${child}`}
              })
            }
          })
          return treeData
        }}
      />
      <ProFormSelect
        name="dy_tag"
        label="抖音Tag"
        mode="multiple"
        showSearch
        request={async ({keyWords}) => {
          if (!keyWords) return []
          const res = await firstValueFrom(IHttp.suggestDyTag(keyWords))
          if (!res.status) return []
          return res.data.map((item: any) => {
            const itemKey = `${item.cha_name}_${new Intl.NumberFormat('zh-CN', { notation: "compact" }).format(item.view_count)}_${item.cid}_${item.group_id}`
            return {label: itemKey, value: itemKey}
            return {
              ...item,
              value: `${item.cid}_${item.group_id}`, 
              label: `${item.cha_name}  ${new Intl.NumberFormat('zh-CN', { notation: "compact" }).format(item.view_count)}`,
            }
          })
        }}
      />
    </DrawerForm>
  )
}
